package com.shuqi.database.dao.impl;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import android.content.Context;
import android.text.TextUtils;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.stmt.Where;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Constant;
import com.shuqi.common.utils.Log4an;
import com.shuqi.database.dao.OrmBaseDao;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.model.bean.CheckBookUpdateInfo;
import com.shuqi.model.manager.FreeBookDownloadManager.DownConstant;

/**
 * 
 * @author yaozhen
 * 
 */
public class BookMarkInfoDao extends OrmBaseDao {

    public static final int SYN_TYPE_SHUQI = 100;

    public static final int SYN_TYPE_SHENMA = 200;

    private static BookMarkInfoDao mInstance;

    private RuntimeExceptionDao<BookMarkInfo, Integer> mDao = ShuqiDatabaseHelper.getHelper(
            ShuqiApplication.getContext()).getRuntimeExceptionDao(BookMarkInfo.class);

    private BookMarkInfoDao(Context context) {

    }

    public static synchronized BookMarkInfoDao getInstance() {
        if (mInstance == null) {
            mInstance = new BookMarkInfoDao(ShuqiApplication.getContext());
        }
        return mInstance;
    }

    /**
     * 填充传入model的空白字段
     * 
     * @param info
     * @param dbInfo
     * @return
     */
    private BookMarkInfo fillBookMarkInfo(BookMarkInfo info, BookMarkInfo dbInfo) {
        if (dbInfo == null) {
            return info;
        }
        if (!TextUtils.isEmpty(info.getSourceId())) {
            dbInfo.setSourceId(info.getSourceId());
        }
        if (!TextUtils.isEmpty(info.getBookId())) {
            dbInfo.setBookId(info.getBookId());
        }
        if (!TextUtils.isEmpty(info.getBookName())) {
            dbInfo.setBookName(info.getBookName());
        }
        if (!TextUtils.isEmpty(info.getChapterId())) {
            dbInfo.setChapterId(info.getChapterId());
        }
        if (!TextUtils.isEmpty(info.getChapterName())) {
            dbInfo.setChapterName(info.getChapterName());
        }
        if (!TextUtils.isEmpty(info.getFilePath())) {
            dbInfo.setFilePath(info.getFilePath());
        }
        if (!TextUtils.isEmpty(info.getPayMode())) {
            dbInfo.setPayMode(info.getPayMode());
        }
        if (!TextUtils.isEmpty(info.getUserId())) {
            dbInfo.setUserId(info.getUserId());
        }
        if (!TextUtils.isEmpty(info.getBookCoverImgUrl())) {
            dbInfo.setBookCoverImgUrl(info.getBookCoverImgUrl());
        }
        if (info.getBookReadByte() >= 0) {
            dbInfo.setBookReadByte(info.getBookReadByte());
        }
        if (info.getPercent() >= 0) {
            dbInfo.setPercent(info.getPercent());
        }
        if (info.getBookTotalByte() >= 0) {
            dbInfo.setBookTotalByte(info.getBookTotalByte());
        }
        if (info.getUpdateFlag() > 0) {
            dbInfo.setUpdateFlag(info.getUpdateFlag());
        }
        if (info.getDeleteFlag() > 0) {
            dbInfo.setDownloadFlag(info.getDeleteFlag());
        }
        if (info.getDownCount() > 0) {
            dbInfo.setDownCount(info.getDownCount());
        }
        if (info.getTotalChapter() > 0) {
            dbInfo.setTotalChapter(info.getTotalChapter());
        }
        return dbInfo;
    }

    /**
     * 获取本地的书签信息
     * 
     * @return
     */
    public List<BookMarkInfo> getLocalBookMarkList() {
        QueryBuilder<BookMarkInfo, Integer> queryBuilder = mDao.queryBuilder();
        Where<BookMarkInfo, Integer> where = queryBuilder.where();
        try {
            where.eq("book_type", BookMarkInfo.TYPE_LOCAL_BOOKMARK);
            return queryBuilder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    //从数据库中读取老的数据，覆盖新obj中没有填充的数据
    private void generateNewMarkInfo(final BookMarkInfo info){
        BookMarkInfo tmpInfo = BookMarkInfoDao.getInstance().getBookMark(info.getSourceId(), info.getBookId(), info.getUserId(), info.getBookType());
        if( tmpInfo != null ){
            if (info.getDownloadFlag() == DownConstant.STATE_NONE) {
                info.setDownloadFlag(tmpInfo.getDownloadFlag());
            }
            if (info.getDownCount() == 0) {
                info.setDownCount(tmpInfo.getDownCount());
            }
            
            if( info.getBookCoverImgUrl() == null && tmpInfo.getBookCoverImgUrl() != null ){
                info.setBookCoverImgUrl(tmpInfo.getBookCoverImgUrl());
            }
            
            if( info.getBookId() == null && tmpInfo.getBookId() != null ){
                info.setBookId(tmpInfo.getBookId());
            } 
            
            if(info.getBookName() == null && tmpInfo.getBookName() != null ){
                info.setBookName(tmpInfo.getBookName());
            }
            
//            if(info.getBookReadByte() == 0 ){
//                info.setBookReadByte(tmpInfo.getBookReadByte());
//            }
            
            if(info.getBookTotalByte() == 0 ){
                info.setBookTotalByte(tmpInfo.getBookTotalByte());
            }
            
            if(info.getBookType() == 0){
                info.setBookType(tmpInfo.getBookType());
            }
            
            if( info.getChapterId() == null && tmpInfo.getChapterId() != null ){
                info.setChapterId(tmpInfo.getChapterId());
            }
            
            if(info.getChapterName() == null && tmpInfo.getChapterName() != null ){
                info.setChapterName(tmpInfo.getChapterName());
            }
            
            if(info.getDeleteFlag() == BookMarkInfo.FLAG_RETAIN ){
                info.setDeleteFlag(tmpInfo.getDeleteFlag());
            }
            
            if(info.getFilePath() == null && tmpInfo.getFilePath() != null ){
                info.setFilePath(tmpInfo.getFilePath());
            }
            
            if(info.getPayMode() == null && tmpInfo.getPayMode() != null ){
                info.setPayMode(tmpInfo.getPayMode());
            }
            
            if(info.getPercent() < 0.001 ){
                info.setPercent(tmpInfo.getPercent());
            }
            
            if(info.getSourceId() == null && tmpInfo.getSourceId() != null ){
                info.setSourceId(tmpInfo.getSourceId());
            }
            
            if(info.getTotalChapter() == 0){
                info.setTotalChapter(tmpInfo.getTotalChapter());
            }
            
            //不要更改更新标志位
//            if(info.getUpdateFlag() == 0){
//                info.setUpdateFlag(tmpInfo.getUpdateFlag());
//            }
            
            if(info.getUpdateTime() == 0 ){
                info.setUpdateTime(tmpInfo.getUpdateTime());
            }
            
            if(info.getUserId() == null && tmpInfo.getUserId() != null){
                info.setUserId(tmpInfo.getUserId());
            }
            
        }
    }

    /**
     * 保存书签信息 需要完整数据 根据不同类型调用不同的保存方法
     * */
    public void updateBookMark(final BookMarkInfo info) {
        if (info == null) {
            return;
        }
        int type = info.getBookType();
        int del = -1;
        info.setUpdateTime(System.currentTimeMillis());
        info.setDeleteFlag(BookMarkInfo.FLAG_RETAIN);
        if (type == BookMarkInfo.TYPE_NEW_PAY_BOOKMARK
                || type == BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK
                || type == BookMarkInfo.TYPE_OLD_WEB_BOOKMARK) {
            generateNewMarkInfo(info);
            del = saveShuqiBookMark(info);
        } else if (type == BookMarkInfo.TYPE_LOCAL_BOOKMARK) {
            generateNewMarkInfo(info);
            del = saveLocalBookMark(info);
        } else if (type == BookMarkInfo.TYPE_OLD_BAG_BOOKMARK) {
            generateNewMarkInfo(info);
            del = saveBookBagMark(info);
        } else if (type == BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK
                || type == BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK) {
            generateNewMarkInfo(info);
            del = saveSheMaBookMark(info);
        }
        if (del == 0) {
            // 判断删除更多的书签
            delMoreBookMark(info.getUserId());
        }
    }
    
    /**
     * 保存书签信息 需要完整数据 根据不同类型调用不同的保存方法
     * */
    public void saveBookMark(final BookMarkInfo info) {
        saveBookMark(info, true);
    }
    
    /**
     * 保存书签信息 需要完整数据 根据不同类型调用不同的保存方法
     * @param info
     * @param isUpdateTime 是否更新书签的时间
     */
    public void saveBookMark(final BookMarkInfo info, boolean isUpdateTime){
        if (info == null) {
            return;
        }
        int type = info.getBookType();
        int del = -1;
        if(isUpdateTime){
            info.setUpdateTime(System.currentTimeMillis());
        }
        info.setDeleteFlag(BookMarkInfo.FLAG_RETAIN);
        if (type == BookMarkInfo.TYPE_NEW_PAY_BOOKMARK
                || type == BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK
                || type == BookMarkInfo.TYPE_OLD_WEB_BOOKMARK) {
            del = saveShuqiBookMark(info);
        } else if (type == BookMarkInfo.TYPE_LOCAL_BOOKMARK) {
            del = saveLocalBookMark(info);
        } else if (type == BookMarkInfo.TYPE_OLD_BAG_BOOKMARK) {
            del = saveBookBagMark(info);
        } else if (type == BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK
                || type == BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK) {
            del = saveSheMaBookMark(info);
        }
        if (del == 0) {
            // 判断删除更多的书签
            delMoreBookMark(info.getUserId());
        }
    }

    /**
     * 导入老库的书签
     * 
     * @param info
     */
    public int saveOldBookMarks(final List<BookMarkInfo> list) {
        if (list == null || list.size() == 0) {
            return -1;
        }
        try {
            Callable<Integer> callble = new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                    int size = 0;
                    for (BookMarkInfo bookMarkInfo : list) {
                        Log4an.e("yzj", "导入老书签  uid="+bookMarkInfo.getUserId());
                        size += mDao.create(bookMarkInfo);
                    }
                    return size;
                }
            };
            int saveSize =
                    (Integer) openTransactionManager(
                            ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()), callble);
            return saveSize;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;

    }


    /**
     * 删除大于300条的书签
     */
    @SuppressWarnings("unchecked")
    private void delMoreBookMark(String uid) {
        QueryBuilder<BookMarkInfo, Integer> queryBuilder = mDao.queryBuilder();
        if (TextUtils.isEmpty(uid)) {
            try {
                Where<BookMarkInfo, Integer> where = queryBuilder.where();
                where.or(where.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_WEB_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_LOCAL_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_BAG_BOOKMARK));
                queryBuilder.orderBy("update_time", true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            // 验证通过对用户
            try {
                Where<BookMarkInfo, Integer> where = queryBuilder.where();
                where.or(where.and(where.or(
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_WEB_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_PAY_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK)), where
                        .eq("user_id", uid)), where.or(
                        where.eq("book_type", BookMarkInfo.TYPE_LOCAL_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_BAG_BOOKMARK)));
                queryBuilder.orderBy("update_time", true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        try {
            if (queryBuilder.countOf() > 300) {
                BookMarkInfo info = queryBuilder.queryForFirst();
                if (info != null) {
                    mDao.delete(info);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量保存本地书签
     */

    /**
     * 保存或者更新BookMarkInfo, 为空的字段会被忽略
     * 
     * @param info
     */
    public void saveOrUpdateBookMark(final BookMarkInfo info) {
        if (info == null || info.getBookType() == 0) {
            return;
        }
        BookMarkInfo dbInfo;
        if (info.getBookType() == BookMarkInfo.TYPE_LOCAL_BOOKMARK) {
            dbInfo = getLocalBookMarkByPath(info.getFilePath());
        } else {
            dbInfo =
                    getBookMark(info.getSourceId(), info.getBookId(), info.getUserId(),
                            info.getBookType());
        }
        BookMarkInfo saveInfo = fillBookMarkInfo(info, dbInfo);
        saveBookMark(saveInfo);

    }

    /**
     * 保存书包书签
     * 
     * @param info
     */
    private int saveBookBagMark(final BookMarkInfo info) {
        if (info == null) {
            return -1;
        }
        try {
            Callable<Integer> callble = new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                    DeleteBuilder<BookMarkInfo, Integer> deleteBuilder = mDao.deleteBuilder();
                    Where<BookMarkInfo, Integer> where = deleteBuilder.where();
                    where.eq("book_id", info.getBookId());
                    where.and().eq("book_type", info.getBookType());
                    int del = deleteBuilder.delete();
                    mDao.create(info);
                    return del;
                }
            };
            int del =
                    (Integer) openTransactionManager(
                            ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()), callble);
            return del;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return -1;
    }

    /**
     * 保存本地书签
     * 
     * @param info
     */
    private int saveLocalBookMark(final BookMarkInfo info) {
        if (info == null || info.getBookType() != BookMarkInfo.TYPE_LOCAL_BOOKMARK
                || TextUtils.isEmpty(info.getFilePath())) {
            return -1;
        }
        try {
            Callable<Integer> callble = new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                    DeleteBuilder<BookMarkInfo, Integer> deleteBuilder = mDao.deleteBuilder();
                    Where<BookMarkInfo, Integer> where = deleteBuilder.where();
                    where.eq("file_path", info.getFilePath());
                    where.and().eq("book_type", BookMarkInfo.TYPE_LOCAL_BOOKMARK);
                    int del = deleteBuilder.delete();
                    mDao.create(info);
                    return del;
                }
            };
            int del =
                    (Integer) openTransactionManager(
                            ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()), callble);
            return del;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 保存 神马app，神马网页的书签
     * 
     * @param info
     */
    private int saveSheMaBookMark(final BookMarkInfo info) {
        if (info == null || TextUtils.isEmpty(info.getBookId())) {
            return -1;
        }
        try {
            Callable<Integer> callble = new Callable<Integer>() {

                @SuppressWarnings("unchecked")
                @Override
                public Integer call() throws Exception {
                    DeleteBuilder<BookMarkInfo, Integer> deleteBuilder = mDao.deleteBuilder();
                    Where<BookMarkInfo, Integer> where = deleteBuilder.where();
                    where.and(where.eq("book_id", info.getBookId()), where.eq("user_id",
                            info.getUserId()), where.or(
                            where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK),
                            where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK)));
                    int del = deleteBuilder.delete();
                    mDao.create(info);
                    return del;
                }
            };
            int del =
                    (Integer) openTransactionManager(
                            ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()), callble);
            return del;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return -1;
    }

    /**
     * 保存 老在线，收费，网页的书签
     * 
     * @param info
     */
    private int saveShuqiBookMark(final BookMarkInfo info) {
        if (info == null) {
            return -1;
        }

        final int type = info.getBookType();
        try {
            Callable<Integer> callble = new Callable<Integer>() {

                @SuppressWarnings("unchecked")
                @Override
                public Integer call() throws Exception {
                    DeleteBuilder<BookMarkInfo, Integer> deleteBuilder = mDao.deleteBuilder();
                    Where<BookMarkInfo, Integer> where = deleteBuilder.where();
                    if (type == BookMarkInfo.TYPE_NEW_PAY_BOOKMARK) {
                        where.and(where.or(
                                where.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                                where.eq("book_type", BookMarkInfo.TYPE_NEW_PAY_BOOKMARK)), where
                                .and(where.eq("book_id", info.getBookId()),
                                        where.eq("user_id", info.getUserId())));
                    } else {
                        where.eq("book_id", info.getBookId());
                        where.and().eq("book_type", type);
                        where.and().eq("user_id", info.getUserId());
                    }
                    int del = deleteBuilder.delete();
                    mDao.create(info);
                    return del;
                }
            };
            int del =
                    (Integer) openTransactionManager(
                            ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()), callble);
            return del;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 根据书签type，sourceId，bookId, uid 查询书签
     * 
     * @return
     */
    public BookMarkInfo getBookMark(String sourceId, String bookId, String uid, int type) {
        if (TextUtils.isEmpty(bookId) || TextUtils.isEmpty(uid)) {
            return null;
        }
        QueryBuilder<BookMarkInfo, Integer> queryBuilder = mDao.queryBuilder();
        try {
            Where<BookMarkInfo, Integer> where = queryBuilder.where();
            where.eq("book_id", bookId);
            if (!TextUtils.isEmpty(sourceId)) {
                where.and().eq("source_id", sourceId);
            }
            where.and().eq("book_type", type);
            where.and().eq("user_id", uid);
            where.and().eq("delete_flag", BookMarkInfo.FLAG_RETAIN);
            List<BookMarkInfo> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * 查询书包书签
     * @return
     */
    public BookMarkInfo getBookBagMark(String bookId) {
        if (TextUtils.isEmpty(bookId)) {
            return null;
        }
        QueryBuilder<BookMarkInfo, Integer> queryBuilder = mDao.queryBuilder();
        try {
            Where<BookMarkInfo, Integer> where = queryBuilder.where();
            where.eq("book_id", bookId);
            where.and().eq("book_type", BookMarkInfo.TYPE_OLD_BAG_BOOKMARK);
            where.and().eq("delete_flag", BookMarkInfo.FLAG_RETAIN);
            List<BookMarkInfo> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据本地的路径获取书签信息
     * 
     * @return
     */
    public BookMarkInfo getLocalBookMarkByPath(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        QueryBuilder<BookMarkInfo, Integer> queryBuilder = mDao.queryBuilder();
        try {
            Where<BookMarkInfo, Integer> where = queryBuilder.where();
            where.eq("file_path", filePath);
            where.and().eq("delete_flag", BookMarkInfo.FLAG_RETAIN);
            List<BookMarkInfo> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取需要云同步的书签
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<BookMarkInfo> getSynBookMarkList(String uid, long updateTime) {

        if (TextUtils.isEmpty(uid) || Constant.GUEST_USER_ID.equals(uid)) {
            return null;
        }

        QueryBuilder<BookMarkInfo, Integer> queryBuilder = mDao.queryBuilder();
        try {
            Where<BookMarkInfo, Integer> where = queryBuilder.where();
            where.and(
                    where.eq("user_id", uid),
                    where.or(where.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                            where.eq("book_type", BookMarkInfo.TYPE_NEW_PAY_BOOKMARK),
                            where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK),
                            where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK)),
                    where.gt("update_time", updateTime));
            List<BookMarkInfo> list = queryBuilder.query();
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存同步书签（先删除所有可云同步的书签，再保存最终的）
     * @param uid
     * @param map
     */
    public void saveSynBookMarkList(final String uid, final Map<String, BookMarkInfo> map) {
        if (TextUtils.isEmpty(uid) || Constant.GUEST_USER_ID.equals(uid)) {
            return;
        }

        try {
            Callable<Void> callble = new Callable<Void>() {

                @SuppressWarnings("unchecked")
                @Override
                public Void call() throws Exception {
                    DeleteBuilder<BookMarkInfo, Integer> delBuilder = mDao.deleteBuilder();
                    Where<BookMarkInfo, Integer> delWhere = delBuilder.where();
                    delWhere.and(delWhere.eq("user_id", uid), delWhere.or(
                            delWhere.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                            delWhere.eq("book_type", BookMarkInfo.TYPE_NEW_PAY_BOOKMARK),
                            delWhere.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK),
                            delWhere.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK)));
                    delBuilder.delete();
                    if (map != null && map.size() > 0) {
                        Collection<BookMarkInfo> values = map.values();
                        for (BookMarkInfo bookMarkInfo : values) {
                            mDao.create(bookMarkInfo);
                        }
                    }
                    return null;
                }
            };
            openTransactionManager(ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callble);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 保存云同步书签（存在：更新阅读进度，不存在：新增）
     * @param uid 
     * @param map
     */
    @SuppressWarnings("unchecked")
    public void updateSaveSynBookMark(final String uid, final Map<String, BookMarkInfo> map) {
        if (TextUtils.isEmpty(uid) || Constant.GUEST_USER_ID.equals(uid)) {
            return;
        }
        if (map != null && map.size() > 0) {
            Collection<BookMarkInfo> values = map.values();
            int index = 0;
            for (BookMarkInfo bookMarkInfo : values) {
                Log4an.e("SyncBookMarks", "updateSaveSynBookMark update Index: "+index);
                updateSaveSynBookMark(uid, bookMarkInfo);
                index++;
            }
            //删除不存在的书签
            DeleteBuilder<BookMarkInfo, Integer> delBuilder = mDao.deleteBuilder();
            Where<BookMarkInfo, Integer> delWhere = delBuilder.where();
            try {
                delWhere.and(delWhere.eq("user_id", uid),delWhere.eq("delete_flag", BookMarkInfo.FLAG_DELETE), delWhere.or(
                        delWhere.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                        delWhere.eq("book_type", BookMarkInfo.TYPE_NEW_PAY_BOOKMARK),
                        delWhere.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK),
                        delWhere.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK)));
                int num = delBuilder.delete();
                Log4an.i("SyncBookMarks", "delte bookMark Num of delete "+num);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
        }
    }
    /**
     * 保存云同步书签（存在：更新阅读进度，不存在：新增）
     * @param uid
     * @param bookMark
     */
    private void updateSaveSynBookMark(final String uid, final BookMarkInfo bookMark) {
        if (TextUtils.isEmpty(uid) || Constant.GUEST_USER_ID.equals(uid) || bookMark==null) {
            return;
        }
        try {
            Callable<Void> callble = new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    UpdateBuilder<BookMarkInfo, Integer> updateBuilder = mDao.updateBuilder();
                    Where<BookMarkInfo, Integer> updateWhere = updateBuilder.where();
                    updateWhere.eq("user_id", uid);
                    updateWhere.and().eq("book_id", bookMark.getBookId());
                    updateWhere.and().eq("book_type", bookMark.getBookType());
                    
                    updateBuilder.updateColumnValue("book_name", bookMark.getBookName());
                    updateBuilder.updateColumnValue("chapter_id", bookMark.getChapterId());
                    updateBuilder.updateColumnValue("chapter_name", bookMark.getChapterName());
                    updateBuilder.updateColumnValue("book_read_byte", bookMark.getBookReadByte());
                    updateBuilder.updateColumnValue("book_total_byte", bookMark.getBookTotalByte());
                    updateBuilder.updateColumnValue("percent", bookMark.getPercent());
                    updateBuilder.updateColumnValue("total_chapter", bookMark.getTotalChapter());
                    updateBuilder.updateColumnValue("update_time", bookMark.getUpdateTime());
                    if(!TextUtils.isEmpty(bookMark.getBookCoverImgUrl())){
                        updateBuilder.updateColumnValue("bookcover_img_url", bookMark.getBookCoverImgUrl());
                    }else{
                        Log4an.e("SyncBookMarks", "updateSaveSynBookMark: img null "+bookMark.getBookName());
                    }
                    int num = updateBuilder.update();
                    Log4an.i("SyncBookMarks", "updateSaveSynBookMark:num="+num);
                    if(num==0){
                        saveBookMark(bookMark, bookMark.getUpdateTime() <= 0);
                    }
                    return null;
                }
            };
            openTransactionManager(ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callble);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 书架展示
     * 
     * @param uid
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<BookMarkInfo> getBookShefBookMarkList(String uid) {
        QueryBuilder<BookMarkInfo, Integer> queryBuilder = mDao.queryBuilder();

        // 未验证的用户
        if (TextUtils.isEmpty(uid)) {
            try {
                Where<BookMarkInfo, Integer> where = queryBuilder.where();
                where.and(where.or(where.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_WEB_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_LOCAL_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_BAG_BOOKMARK)), where.eq(
                        "delete_flag", BookMarkInfo.FLAG_RETAIN));
                queryBuilder.orderBy("update_time", false);
                return queryBuilder.query();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            // 验证通过对用户
            try {
                Where<BookMarkInfo, Integer> where = queryBuilder.where();
                where.or(where.and(where.or(
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_WEB_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_PAY_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK)), where
                        .and(where.eq("user_id", uid),
                                where.eq("delete_flag", BookMarkInfo.FLAG_RETAIN))), where.or(
                        where.eq("book_type", BookMarkInfo.TYPE_LOCAL_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_BAG_BOOKMARK)));
                queryBuilder.orderBy("update_time", false);
                return queryBuilder.query();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    /**
     * 
     * @param uid
     * @param bid
     * @param bookType
     * @return
     */
    public int updateBookMarkDownloadState(String uid, String bid, int bookType, int downState,
            int downCount) {
        if (TextUtils.isEmpty(uid) || TextUtils.isEmpty(bid)) {
            return -1;
        }
        UpdateBuilder<BookMarkInfo, Integer> updateBuilder = mDao.updateBuilder();
        Where<BookMarkInfo, Integer> where = updateBuilder.where();
        try {
            where.eq("user_id", uid);
            where.and().eq("book_id", bid);
            where.and().eq("book_type", bookType);
            updateBuilder.updateColumnValue("download_flag", downState);
            updateBuilder.updateColumnValue("download_count", downCount);
            return updateBuilder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 更新书籍的总章节数
     * 
     * @param uid
     * @param bid
     * @param totalCount
     * @return
     */
    public int updateBookMarkDownloadTotalCount(String uid, String bid, int bookType,
            int downState, int totalCount) {
        if (TextUtils.isEmpty(uid) || TextUtils.isEmpty(bid)) {
            return -1;
        }
        UpdateBuilder<BookMarkInfo, Integer> updateBuilder = mDao.updateBuilder();
        Where<BookMarkInfo, Integer> where = updateBuilder.where();
        try {
            where.eq("user_id", uid);
            where.and().eq("book_id", bid);
            where.and().eq("book_type", bookType);
            updateBuilder.updateColumnValue("download_flag", downState);
            updateBuilder.updateColumnValue("total_chapter", totalCount);
            return updateBuilder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }


    /**
     * 检查更新 更新书签
     * 
     * @param uid
     */
    public void updateBookMark(final String uid, final List<CheckBookUpdateInfo> list) {
        if (TextUtils.isEmpty(uid) || list == null || list.size() == 0) {
            return;
        }
        // 更新书签表
        Callable<Void> callable = new Callable<Void>() {

            @Override
            public Void call() throws Exception {

                for (CheckBookUpdateInfo checkBookUpdateInfo : list) {
                    UpdateBuilder<BookMarkInfo, Integer> updateBuilder = mDao.updateBuilder();
                    Where<BookMarkInfo, Integer> where = updateBuilder.where();
                    where.eq("book_id", checkBookUpdateInfo.getBookId());
                    where.and().eq("user_id", uid);
                    if (!TextUtils.isEmpty(checkBookUpdateInfo.getSourceId())) {
                        where.and().eq("source_id", checkBookUpdateInfo.getSourceId());
                    } else {
                        where.and().eq("book_type", BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
                    }
                    if(CheckBookUpdateInfo.UPDATETYPE_PAYMODE.equals(checkBookUpdateInfo.getUpdateType())){
                        Log4an.i("payMode update name="+checkBookUpdateInfo.getBookName());
                    }else{
                        Log4an.i("chapter update name="+checkBookUpdateInfo.getBookName());
                        updateBuilder.updateColumnValue("update_flag", BookMarkInfo.UPDATE_FLAG);
                    }
                    updateBuilder.updateColumnValue("total_chapter",
                            checkBookUpdateInfo.getMaxOid());
                    updateBuilder.update();
                }

                return null;
            }

        };
        try {
            openTransactionManager(ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callable);
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

    /**
     * 
     * @param uid
     * @param updateType 100 表示书旗书签 合并在线 收费 200 表示神马书签 神马app 神马wap
     * @param count
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<BookMarkInfo> getUpdateBookMarkList(String uid, int updateType, int count) {
        if (TextUtils.isEmpty(uid)) {
            return null;
        }
        QueryBuilder<BookMarkInfo, Integer> queryBuilder = mDao.queryBuilder();
        Where<BookMarkInfo, Integer> where = queryBuilder.where();
        if (updateType == SYN_TYPE_SHUQI) {
            try {
                where.and(where.eq("user_id", uid), where.or(
                        where.eq("book_type", BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_PAY_BOOKMARK)), where.eq(
                        "delete_flag", BookMarkInfo.FLAG_RETAIN));
                queryBuilder.limit(Long.valueOf(count));
                return queryBuilder.query();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        } else if (updateType == SYN_TYPE_SHENMA) {
            try {
                where.and(where.eq("user_id", uid), where.or(
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK),
                        where.eq("book_type", BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK)), where
                        .eq("delete_flag", BookMarkInfo.FLAG_RETAIN));
                queryBuilder.limit(Long.valueOf(count));
                return queryBuilder.query();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 删除 根据type 判断是否彻底删除， 需要云同步的不删除，只是更新delflag字段
     */
    public int delBookMark(BookMarkInfo bookMarkInfo) {
        if (bookMarkInfo == null) {
            return -1;
        }
        int type = bookMarkInfo.getBookType();
        if (type == BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK
                || type == BookMarkInfo.TYPE_NEW_PAY_BOOKMARK
                || type == BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK
                || type == BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK) {
            // 云同步书签不删除
            UpdateBuilder<BookMarkInfo, Integer> updateBuilder = mDao.updateBuilder();
            Where<BookMarkInfo, Integer> where = updateBuilder.where();
            try {
                where.eq("user_id", bookMarkInfo.getUserId());
                where.and().eq("book_type", bookMarkInfo.getBookType());
                where.and().eq("book_id", bookMarkInfo.getBookId());
                updateBuilder.updateColumnValue("delete_flag", BookMarkInfo.FLAG_DELETE);
                updateBuilder.updateColumnValue("update_time", System.currentTimeMillis());
                return updateBuilder.update();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        } else {
            DeleteBuilder<BookMarkInfo, Integer> delteBuilder = mDao.deleteBuilder();
            Where<BookMarkInfo, Integer> where = delteBuilder.where();
            try {
                where.eq("book_type", bookMarkInfo.getBookType());
                if (!TextUtils.isEmpty(bookMarkInfo.getUserId())) {
                    where.and().eq("user_id", bookMarkInfo.getUserId());
                }
                if (!TextUtils.isEmpty(bookMarkInfo.getBookId())) {
                    where.and().eq("book_id", bookMarkInfo.getBookId());;
                }
                if (!TextUtils.isEmpty(bookMarkInfo.getSourceId())) {
                    where.and().eq("source_id", bookMarkInfo.getSourceId());
                }
                if (!TextUtils.isEmpty(bookMarkInfo.getFilePath())) {
                    where.and().eq("file_path", bookMarkInfo.getFilePath());
                }
                return delteBuilder.delete();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return -1;
    }

    /**
     * 删除 根据type 判断是否彻底删除， 需要云同步的不删除，只是更新delflag字段
     */
    public void delBookMarkList(final List<BookMarkInfo> list) {
        Callable<Void> callble = new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                for (BookMarkInfo bookMarkInfo : list) {
                    delBookMark(bookMarkInfo);
                }
                return null;
            }
        };
        try {
            openTransactionManager(ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callble);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除神马的标签 type 为 8
     * 
     * @param list
     * @return
     */
    public void delShenMaBookMarkList(final List<BookMarkInfo> list, final boolean delFile) {
        Callable<Void> callble = new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                for (BookMarkInfo bookMarkInfo : list) {
                    // 删除书籍
                    delBookMark(bookMarkInfo);
                    // 更新书籍数据库
                    BookInfoDao.getInstance().updateBookInfoAfterBookMark(bookMarkInfo.getBookId(),
                            bookMarkInfo.getSourceId(), bookMarkInfo.getUserId());
                    if(delFile){
                        
                        // 删除目录数据库
                        BookCataLogDao.getInstance().deleteBookCatalogByBookId(
                                bookMarkInfo.getBookId(), bookMarkInfo.getSourceId(),
                                bookMarkInfo.getUserId());
                    }
                }
                return null;
            }
        };
        try {
            openTransactionManager(ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callble);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除神马的标签 type 为 1,9
     * 
     * @param list
     * @return
     */
    public void delShuqiBookMarkList(final List<BookMarkInfo> list, final boolean isDelFile) {
        Callable<Void> callble = new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                for (BookMarkInfo bookMarkInfo : list) {
                    // 删除书籍，
                    delBookMark(bookMarkInfo);
                    // 更新书籍数据库
                    BookInfoDao.getInstance().updateBookInfoAfterBookMark(bookMarkInfo.getBookId(),
                            bookMarkInfo.getSourceId(), bookMarkInfo.getUserId());
                    if(isDelFile){
                        
                        // 删除目录数据库
                        BookCataLogDao.getInstance().deleteBookCatalogByBookId(
                                bookMarkInfo.getBookId(), bookMarkInfo.getSourceId(),
                                bookMarkInfo.getUserId());
                    }

                }
                return null;
            }
        };
        try {
            openTransactionManager(ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callble);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
